// src/stores/vehicle.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 车辆数据接口
export interface Vehicle {
  id: number;
  vehicleId: string;
  brand: string;
  model: string;
  licensePlate: string;
  status: string;
  createTime: string;
}

// 车辆表单字段配置
export const vehicleFields = [
  {
    key: 'vehicleId',
    label: '车辆编号',
    type: 'text',
    placeholder: '请输入车辆编号（如 V001）',
    maxLength: 10,
  },
  {
    key: 'brand',
    label: '品牌',
    type: 'text',
    placeholder: '请输入品牌',
    maxLength: 20,
  },
  {
    key: 'model',
    label: '型号',
    type: 'text',
    placeholder: '请输入型号',
    maxLength: 20,
  },
  {
    key: 'licensePlate',
    label: '车牌号',
    type: 'text',
    placeholder: '请输入车牌号（如 京A12345）',
    maxLength: 7,
  },
  {
    key: 'status',
    label: '状态',
    type: 'select',
    placeholder: '请选择状态',
  },
];

export const useVehicleStore = defineStore('vehicle', {
  state: () => ({
    vehicles: [] as Vehicle[],
  }),
  actions: {
    // 获取车辆列表（无分页）
    async fetchVehicles() {
      try {
        const response = await axios.get('/vehicles');
        if (response.data.code === 200) {
          this.vehicles = response.data.data;
          return this.vehicles;
        }
        throw new Error(response.data.message || '获取车辆列表失败');
      } catch (error) {
        throw new Error('获取车辆列表失败');
      }
    },
    // 创建车辆
    async createVehicle(data: { vehicleId: string; brand: string; model: string; licensePlate: string; status: string }) {
      const response = await axios.post('/vehicles', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '创建车辆失败');
    },
    // 更新车辆
    async updateVehicle(data: Vehicle) {
      const response = await axios.put('/vehicles', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '更新车辆失败');
    },
    // 删除车辆
    async deleteVehicle(id: number) {
      const response = await axios.delete(`/vehicles/${id}`);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '删除车辆失败');
    },
  },
});